/*
 * @Description:
 * @Version: 2.0
 * @Autor: jl.g
 * @Date: 2023-04-09 18:14:13
 * @LastEditors: jl.g
 * @LastEditTime: 2023-09-01 08:47:45
 */
import React, { useState, useEffect, useRef } from "react";
import { setSessionStorage, formatAmount } from "@/utils";
import { useHistory } from "react-router-dom";
import { accountBalance, alertGiveCurrency, userConsumerLog } from "@/api/user";
import { useSelector, useDispatch } from "react-redux";
import { Modal } from "antd";
import currencyIcon from "../../../public/assets/imgs/currencyIcon.svg";
import {
  setActiveMenuItemKey,
  accountInfoAction,
  userConsumerAction,
} from "@/store/actions/home_action";
import ConsumptionRecords from "./ConsumptionRecords";
import styles from "./index.module.less";
const PromptsTemplate = () => {
  // 消费记录ref
  const consumptionRecordsRef = useRef(null);
  const history = useHistory();
  const dispatch = useDispatch();
  let activeMenuItemKey = useSelector((state) => state.activeMenuItemKey);
  const [selectMenuKey, setSelectMenuKey] = useState(Number(activeMenuItemKey));

  // 导航列表
  const tabsDataListPc = useSelector((state) => state.tabsDataListPc);

  // 账户余额变动
  const accountChange = useSelector((state) => state.accountChange);

  // 系统信息
  const sysConfig = useSelector((state) => state.sysConfig);
  console.log(sysConfig, "sysConfig");
  // 账户余额
  const [account, setAccount] = useState(0);
  // 消费记录
  const consumptionRecordsFn = () => {
    consumptionRecordsRef.current.getPage();
  };
  // 菜单点击
  const mentItemClick = ({ id, path }) => {
    // 知识库需要打开新页面
    if (id === 5) {
      let origin = window.location.origin;
      let url = origin + "/#" + path;
      window.open(url);
      return;
    }

    if (path) {
      setSelectMenuKey(id);
      history.replace(path);
      setSessionStorage("activeMenuItemKey", id);
      dispatch(setActiveMenuItemKey(id));
    }
  };

  // 获取账户余额
  const getAccountBalance = async () => {
    try {
      let res = await accountBalance();
      if (res.code === 200) {
        console.log(res.code, "余额");
        setAccount(res.result);
        dispatch(accountInfoAction(res.result));
        if (res.result?.tokenBalance <= 0) {
          //alertGiveCurrencyFn();
        }
      }
    } catch (error) {
      console.log(error);
    }
  };

  // 获取当前消费具体数量
  const userConsumerLogFn = async () => {
    try {
      let res = await userConsumerLog();
      if (res.code === 200) {
        let resData = res.result || null;
        dispatch(userConsumerAction(resData));
      }
    } catch (error) {
      console.log(error);
    }
  };

  // 账户为0的时候如果有送金币活动，弹窗送金币
  const alertGiveCurrencyFn = async () => {
    try {
      let res = await alertGiveCurrency();
      if (res.code === 200) {
        let tokenNums = res.result || 0;
        Modal.success({
          title: "尊敬的用户您好~",
          content: `为感谢您使用本平台，今日免费赠送您 ${tokenNums},已发放到您的账户，请注意查收`,
        });
        setTimeout(() => {
          getAccountBalance();
        }, 1000);
      }
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getAccountBalance();
  }, []);

  useEffect(() => {
    if (accountChange) {
      setTimeout((v) => {
        async function asyncFn() {
          await getAccountBalance();
          // 查询本次具体消耗额度
          await userConsumerLogFn();
        }

        asyncFn();
      }, 1 * 1000);
    }
  }, [accountChange]);

  useEffect(() => {
    if (activeMenuItemKey) {
      console.log(tabsDataListPc, "tabsDataListPc222");
      console.log(activeMenuItemKey, "activeMenuItemKey222");
      setSelectMenuKey(Number(activeMenuItemKey));
    }
  }, [activeMenuItemKey]);
  return (
    <div className={styles.promptsTemplateWarp}>
      <div className="prompts_template-box">
        {tabsDataListPc.map((v) => (
          <div
            key={v.id}
            onClick={() => mentItemClick(v)}
            className={`prompts-menu_item ${
              selectMenuKey === Number(v.id) ? "prompts-selected-item" : ""
            }`}
          >
            <img className="menu-item-icon" src={v.icon} alt="" />
            <div className="menu-item-label">{v.label}</div>
          </div>
        ))}
      </div>

      <div className="account_box">
      {/*<div className="account_box" onClick={consumptionRecordsFn}>*/}
        {/*<div className="label">*/}
        {/*  <img className="currencyIcon" src={currencyIcon} alt="" />*/}
        {/*</div>*/}
        {/*<div className="account_num">*/}
        {/*  {formatAmount(account?.tokenBalance >= 0 ? account.tokenBalance : 0)}*/}
        {/*</div>*/}

        <div className="webVersion">版本号:v:{sysConfig?.webVersion}</div>
      </div>

      {/* 消费记录 */}
      <ConsumptionRecords ref={consumptionRecordsRef}></ConsumptionRecords>
    </div>
  );
};

export default PromptsTemplate;
